package com.iotstudio.embeddedcloudplatform.service.serviceImp;

import com.iotstudio.embeddedcloudplatform.POJO.DO.Role;
import com.iotstudio.embeddedcloudplatform.POJO.DO.RolePermission;
import com.iotstudio.embeddedcloudplatform.POJO.DO.UserRole;
import com.iotstudio.embeddedcloudplatform.POJO.DTO.RoleDTO;
import com.iotstudio.embeddedcloudplatform.dao.PermissionMapper;
import com.iotstudio.embeddedcloudplatform.dao.RoleMapper;
import com.iotstudio.embeddedcloudplatform.dao.RolePermissionMapper;
import com.iotstudio.embeddedcloudplatform.dao.UserRoleMapper;
import com.iotstudio.embeddedcloudplatform.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author BeFondOfTaro
 * Created at 23:13 2018/3/16
 */
@Service
public class RoleServiceImp implements RoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public RoleDTO getRoleDTOById(String roleId) {
        RoleDTO roleDTO = new RoleDTO();
        //角色id
        roleDTO.setId(roleId);
        //角色名
        roleDTO.setName(roleMapper.selectByPrimaryKey(roleId).getName());
        List<RolePermission> rolePermissionList = rolePermissionMapper.selectByRoleId(roleId);
        //权限列表
        for (RolePermission rolePermission : rolePermissionList){
            roleDTO.getPermissionList().add(
                    permissionMapper.selectByPrimaryKey(rolePermission.getPermissionId())
            );
        }
        return roleDTO;
    }

    @Override
    public List<Role> listRoleByUserId(String userId) {
        List<Role> roleList = new ArrayList<>();
        List<UserRole> userRoleList = userRoleMapper.getUserRoleByUserId(userId);
        for (UserRole userRole : userRoleList){
            roleList.add(roleMapper.selectByPrimaryKey(userRole.getRoleId()));
        }
        return roleList;
    }
}
